package com.it.system.user.filter;

import com.it.system.educommonapi.util.JwtUtils;
import com.it.system.educommonapi.util.RsaUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;

    @Autowired
    public JwtAuthenticationFilter(@Qualifier("userDetailsServiceImpl") UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        log.info("JwtAuthenticationFilter 收到请求: {}, Authorization: {}", request.getRequestURI(), token);
        
        if (token != null) {
            // 如果token以"Bearer "开头，则去掉这个前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            try {
                String username = JwtUtils.getUsernameFromToken(token, RsaUtils.publicKey);
                log.info("JwtAuthenticationFilter 从token中解析出用户名: {}", username);
                
                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    try {
                        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                        log.info("JwtAuthenticationFilter 成功加载用户详情: {}", userDetails.getUsername());
                        
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        log.info("JwtAuthenticationFilter 已设置认证信息到SecurityContext");
                    } catch (Exception e) {
                        log.error("JwtAuthenticationFilter 加载用户详情失败: {}", e.getMessage(), e);
                    }
                }
            } catch (Exception e) {
                log.error("JwtAuthenticationFilter 无法设置用户认证: {}", e.getMessage(), e);
            }
        } else {
            log.info("JwtAuthenticationFilter 请求没有Authorization头");
        }
        
        log.info("JwtAuthenticationFilter 继续过滤器链");
        filterChain.doFilter(request, response);
    }
} 